package com.quan.Comfirm;

import com.quan.Config.MQConnection;
import com.rabbitmq.client.*;
import org.junit.Test;

import java.io.IOException;

public class publisher {
    @Test
    public void publisher() throws Exception{
        //创建连接
        Connection conn = MQConnection.getRabbitmaConection();

        //创建channel
        Channel channel = conn.createChannel();

        //发布消息到exchange
        //普通的comfirm方式
       /* channel.confirmSelect();

        String msg = "Hello-World";
        channel.basicPublish("","HelloWorld",null,msg.getBytes());

        if(channel.waitForConfirms()){
            System.out.println("生产者发布消息成功");
        }else{
            System.out.println("生产者发布消息失败");
        }*/


        //批量的comfirm方式
        /*channel.confirmSelect();

        for(int i = 0; i < 1000; i ++){
            String msg = "Hello-World" + i;
            channel.basicPublish("","HelloWorld",null,msg.getBytes());
        }

        channel.waitForConfirmsOrDie();//发送消息有一个失败，那么就全部失败IOException。*/


        //开启return机制
        channel.addReturnListener(new ReturnListener() {
            public void handleReturn(int i, String s, String s1, String s2, AMQP.BasicProperties basicProperties, byte[] bytes) throws IOException {
                //当消息没有发送到队列时就会执行这个方法。
                System.out.println(new String(bytes,"UTF-8")+ "没有送达到队列中！！");
            }
        });

        //异步comfirm方式
        channel.confirmSelect();

        for(int i = 0; i < 1000; i ++){
            String msg = "Hello-World" + i;
            //channel.basicPublish("","HelloWorld",true,null,msg.getBytes());
            channel.basicPublish("","HelloWorldxx",true,null,msg.getBytes());
        }

        channel.addConfirmListener(new ConfirmListener() {
            public void handleAck(long l, boolean b) throws IOException {
                System.out.println("消息发送成功");
            }

            public void handleNack(long l, boolean b) throws IOException {
                System.out.println("消息发送失败");
            }
        });


        System.in.read();
        //释放资源
        channel.close();
        conn.close();

    }
}
